<!--
  - Copyright (c) 2012 The Chromium Authors. All rights reserved.
  - Use of this source code is governed by a BSD-style license that can be
  - found in the LICENSE file.
  -->
<!doctype html>
<html>
  <head>
    <script src="handlebars-1.0.0.beta.6.js"></script>
  </head>
  <body>

    <script id="sample-template-1" type="text/x-handlebars-template">
      <div class="entry">
        <h1>Hello</h1>
        <p>This is a Handlebar template compiled inside a hidden sandboxed iframe.</p>
        <p>The counter parameter from postMessage (outer frame) is: {{counter}}</p>
      </div>
    </script>

    <script id="sample-template-2" type="text/x-handlebars-template">
      <div class="entry">
        <h1>Welcome back</h1>
        <p>This is another Handlebar template compiled inside a hidden sandboxed iframe.</p>
        <p>The counter parameter from postMessage (outer frame) is: {{counter}}</p>
      </div>
    </script>

    <script>
      var templatesElements = document.querySelectorAll("script[type='text/x-handlebars-template']"),
          templates = {},
          source, name;

      // precompile all templates in this page
      for (var i=0; i<templatesElements.length; i++) {
        source = templatesElements[i].innerHTML;
        name = templatesElements[i].id;
        templates[name] = Handlebars.compile(source);
      }

      // Set up message event handler:
      window.addEventListener('message', function(event) {
        var command = event.data.command,
            template = templates[event.data.templateName],
            result = "invalid request";

        // if we don't know the templateName requested, return an error message
        if (!template) {
          result = 'Unknown template: ' + event.data.templateName;
        } else {
          switch(command) {
            case 'render':
              result = template(event.data.context);
              break;
          // you could even do dynamic compilation, by accepting a command
          // to compile a new template instead of using static ones, for example:
          // case 'new':
          //   template = Handlebars.compile(event.data.templateSource);
          //   result = template(event.data.context);
          //   break;
          }
        }
        event.source.postMessage({'result': result}, event.origin);
      });
    </script>
  </body>
</html>
